package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.query.LessonQueryObject;
import cn.wolfcode.crm.service.ILessonService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
;import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("lesson")
public class LessonController {
    @Autowired
    private ILessonService lessonService;

    @RequiresPermissions(value = {"lesson:view", "课程查看"}, logical = Logical.OR)
    @RequestMapping("view")
    public String view() {
        return "lesson/lesson";
    }   //

    @RequiresPermissions(value = {"lesson:query", "课程列表"}, logical = Logical.OR)
    @RequestMapping("query")
    @ResponseBody
    public PageResult query(LessonQueryObject qo) {
        return lessonService.quey4List(qo);
    }

    //导入课程前，将Class信息查出来
    @RequestMapping("getClassById")
    @ResponseBody
    public void getClassById(Long clzId) {
        try {
            lessonService.getClassById(clzId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //导入课程
    @RequestMapping("importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file, HttpServletResponse response) throws Exception {
        JsonResult result = new JsonResult();
        try {
            if (file.getSize() == 0){
                return result.mark("请上传课程表");
            }
            lessonService.importXls(file, response);

        } catch (Exception e) {
            e.printStackTrace();
            result.mark("操作失败!原因:" + e.getMessage());
        }
        return result;
    }


    /**
     * 获取文件上传模板
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("getImportXlsMode")
    public void importXlsMode(HttpServletResponse response) throws Exception {
        //设置文件下载响应头

        response.setHeader("Content-Disposition", "attachment;filename=lesson.xls");

        Workbook book = lessonService.getImportXlsMode();

        //写入数据输出到浏览器
        book.write(response.getOutputStream());
    }
}
